package com.qingyun.customview.autosearch

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.widget.addTextChangedListener
import com.qingyun.customview.R
import com.qingyun.customview.databinding.ActivityEdittextBinding

class EditTextActivity : AppCompatActivity() {
    private lateinit var binding: ActivityEdittextBinding
    private lateinit var mAutoSearchHandler: AutoSearchHandler
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityEdittextBinding.inflate(layoutInflater)
        enableEdgeToEdge()
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        initAutoSearchHandler()
    }

    private fun initAutoSearchHandler() {
        mAutoSearchHandler = AutoSearchHandler(
            debounceTime = 800,
            minQueryLength = 0,
            onSearch = { query: String ->
                performSearch(query)
            }
        )
        binding.editText.addTextChangedListener {
            mAutoSearchHandler.onQueryChanged(it?.toString())
        }
        mAutoSearchHandler.triggerSearchImmediately("")
    }

    private fun performSearch(query: String) {
        // 执行实际搜索逻辑（如调用API或数据库）
        Log.i("", " ${System.currentTimeMillis()} --- performSearch: $query")
    }

    override fun onDestroy() {
        mAutoSearchHandler.clear()
        super.onDestroy()
    }

    companion object {
        fun start(context: Context) {
            Intent(context, EditTextActivity::class.java).also {
                context.startActivity(it)
            }
        }
    }
}